<?php

namespace app\admin\command;

use app\admin\server\QyApiWeixinServer;
use app\admin\server\WxworkAccessTokenServer;
use app\admin\server\WxworkAccessTokenTxlServer;
use app\adminapi\service\BatchSqlServer;
use Psr\SimpleCache\InvalidArgumentException;
use think\Cache;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use think\Db;
use think\Exception;
use think\Log;

class Synchronizedatatolocal extends Command
{
    protected $customerContactToken;

    protected $encodingAesKey;

    protected $wxkfToken;

    protected $wxkfEncodingAesKey;
    //企业ID
    protected $companyID;
    //客户上下游秘钥
    protected $customerContactSecret;
    //自建应用SCRM应用秘钥
    protected $agentScrmSecret;
    //微信客服秘钥
    protected $openWxkfSecret;
    //打卡应用秘钥
    protected $clockInSecret;

    protected $access_token;
    protected $access_token_txl;

    protected $redis_department_list_key = 'wxwork_department_list';

    protected $redis_user_list_key = 'wxwork_user_list';
    protected $redis_user_list_userid_list_key = 'wxwork_user_list_userid_list';

    protected $redis_batch_get_by_user_key = 'wxwork_batch_get_by_user';
    protected $redis_wxwork_company_customer_key = 'la_wxwork_company_customer';
    protected $redis_local_customer_external_userid_arr = 'wxwork_local_customer_external_userid_arr';
    protected $redis_wxwork_company_worker_worker_id_key = 'local_wxwork_company_worker_worker_id';
    protected $redis_wxwork_company_worker_key = 'local_wxwork_company_worker';
    protected $redis_wxwork_depart_position_key = 'wxwork_depart_position';

    /**
     * @return void
     */
    protected function configure()
    {
        // 指令配置
        $this->setName('synchronizedatatolocal')
            //增加一个命令参数
            ->addArgument('action', Argument::OPTIONAL, "action", '')
            ->addArgument('force', Argument::OPTIONAL, "force", '')
            ->addOption('is_go', null, Option::VALUE_OPTIONAL, 'Enable collaboration', 1) // 是否开启协程:0=不开启,1=开启
            ->setDescription('the synchronizedatatolocal command');
    }

    /**
     * @param Input  $input
     * @param Output $output
     * @return void
     * @throws Exception
     * @throws InvalidArgumentException
     */
    protected function execute(Input $input, Output $output)
    {
        //同步最新数据
        set_time_limit(0);
        ini_set('memory_limit', '-1');

        //获取输入参数
        $action = trim($input->getArgument('action'));
        $force = trim($input->getArgument('force'));
        $is_go = true;
        if($input->hasOption('is_go')) {
            $is_go = (int)$input->getOption('is_go');
            $is_go = $is_go > 1 ? true : false;
        }

        try {
            $this->access_token = WxworkAccessTokenServer::getWxworkAccessToken();
            $this->access_token_txl = WxworkAccessTokenTxlServer::getWxworkAccessToken();
            if($this->access_token) {
                // 根据命令执行
                if($action == 'del') {
                    $this->delRedis();
                    $this->setRedisData($is_go);
                } else {
                    $result = Cache::get($this->redis_wxwork_depart_position_key, null);
                    !empty($result) && is_string($result) && $result = json_decode($result, true);
                    if(empty($result)) {
                        $this->setRedisData($is_go);
                    }
                }
                Db::transaction(function() {
                    //第1步获取企业部门
                    $this->getCompanyDepart();
                    //第2步获取企业职位
                    $this->getCompanyDepartPosition();
                    //第3步获取企业成员
                    $this->getCompanyWorker();
                    //第4步获取客户列表
                    $this->getCompanyCustomerDetail();
                    Db::name('wxwork_dispose')
                        ->where('dis_name', '=', 'customer_last_uptime')
                        ->update([
                            'dis_value' => get_now_date('Y-m-d')
                        ]);
                });
            }
        } catch(Exception $e) {
            if($is_go) {
                echo $e->getMessage();
            }
        }
        if($is_go) {
            echo 'SUCCESS';
        }
    }


    /**
     * @return true
     * @throws Exception
     * @throws InvalidArgumentException
     */
    public function setRedisData($is_go = true)
    {
        $this->access_token = WxworkAccessTokenServer::getWxworkAccessToken();
        file_put_contents('./Synchronizedatatolocal.txt', 'setRedisData::start:' . time() . PHP_EOL . PHP_EOL);
        try {
            $expiration_time = strtotime(date('Y-m-d 23:59:59'));
            $result = Cache::get($this->redis_wxwork_depart_position_key, null);
            !empty($result) && is_string($result) && $result = json_decode($result, true);

            if(empty($result)) {
                $old_data = Db::name('wxwork_depart_position')
                    ->field('depart_id,pos_name')
                    ->select();
                empty($old_data) && $old_data = [];
                Cache::set($this->redis_wxwork_depart_position_key, json_encode($old_data, JSON_UNESCAPED_UNICODE), $expiration_time);
            }
            $result = Cache::get($this->redis_wxwork_company_worker_key, null);
            !empty($result) && is_string($result) && $result = json_decode($result, true);
            if(empty($result)) {
                $local_worker = Db::name('wxwork_company_worker')
                    ->field('id,worker_id,worker_name,worker_department,worker_position,worker_mobile,worker_status,worker_main_department')
                    ->order('id', 'asc')
                    ->select();
                if($local_worker) {
                    $_local_worker = [];
                    foreach($local_worker as $item) {
                        $_local_worker[$item['worker_id']] = $item;
                    }
                    $local_worker = $_local_worker;
                }
                Cache::set($this->redis_wxwork_company_worker_key, json_encode($local_worker, JSON_UNESCAPED_UNICODE), $expiration_time);
            }
            $result = Cache::get($this->redis_wxwork_company_customer_key, null);
            !empty($result) && is_string($result) && $result = json_decode($result, true);
            if(empty($result)) {
                //本地
                $local_customer = Db::name('wxwork_company_customer')
                    ->field('id,follow_userid,external_userid,follow_remark,follow_description,follow_createtime,follow_tag_id,follow_remark_mobiles,follow_add_way,external_name,external_type,external_corp_name,external_corp_full_name,follow_state,external_avatar,external_gender')
                    ->select();
                $local_customer_external_userid_arr = [];
                if($local_customer) {
                    foreach($local_customer as $item) {
                        $local_customer_external_userid_arr[] = $item['follow_userid'] . $item['external_userid'];
                    }
                }
                Cache::set($this->redis_local_customer_external_userid_arr, json_encode($local_customer_external_userid_arr, JSON_UNESCAPED_UNICODE), $expiration_time);
                Cache::set($this->redis_wxwork_company_customer_key, json_encode($local_customer, JSON_UNESCAPED_UNICODE), $expiration_time);
            }
            $result = Cache::get($this->redis_department_list_key, null);
            !empty($result) && is_string($result) && $result = json_decode($result, true);
            if(empty($result)) {
                $result = QyApiWeixinServer::getDepartmentList($this->access_token);
                file_put_contents('./Synchronizedatatolocal.txt', 'setRedisData::getDepartmentList:' . json_encode($result) . PHP_EOL . PHP_EOL, FILE_APPEND);
                $data = [];
                foreach($result as $item) {
                    $data[$item['id']] = [
                        'id'               => $item['id'],
                        'depart_name'      => $item['name'],
                        'depart_leader'    => implode(',', $item['department_leader']),
                        'depart_parent_id' => $item['parentid'],
                        'sorts'            => $item['order'],
                    ];
                }
                Cache::set($this->redis_department_list_key, json_encode($data, JSON_UNESCAPED_UNICODE), $expiration_time);
            }
            $result = Cache::get($this->redis_user_list_key, null);
            file_put_contents('./Synchronizedatatolocal.txt', 'setRedisData::redis_user_list_key1:' . $result . PHP_EOL . PHP_EOL, FILE_APPEND);
            !empty($result) && is_string($result) && $result = json_decode($result, true);
            if(empty($result)) {
                $result1 = QyApiWeixinServer::getUserList($this->access_token);
                $redis_user_list_userid_list_key = [];
                foreach($result1 as $item) {
                    $redis_user_list_userid_list_key[$item['userid']] = $item['userid'];
                }
                Cache::set($this->redis_user_list_key, json_encode($result1, JSON_UNESCAPED_UNICODE), $expiration_time);
                Cache::set($this->redis_user_list_userid_list_key, json_encode($redis_user_list_userid_list_key, JSON_UNESCAPED_UNICODE), $expiration_time);
            }
            $result = Cache::get($this->redis_batch_get_by_user_key, null);
            !empty($result) && is_string($result) && $result = json_decode($result, true);
            if(empty($result)) {
                Log::write('redis_batch_get_by_user_key:--------');
                $userIdArr_tmp = [];
                $result = Cache::get($this->redis_wxwork_company_worker_worker_id_key, null);
                !empty($result) && is_string($result) && $result = json_decode($result, true);
                if(empty($result)) {
                    $redis_user_list_userid_list_key = Cache::get($this->redis_user_list_userid_list_key, null);
                    !empty($redis_user_list_userid_list_key) && is_string($redis_user_list_userid_list_key) && $redis_user_list_userid_list_key = json_decode($redis_user_list_userid_list_key, true);
                    if($redis_user_list_userid_list_key) {
                        is_string($redis_user_list_userid_list_key) && $redis_user_list_userid_list_key = json_decode($redis_user_list_userid_list_key, true);
                        $userIdArr_tmp = array_values($redis_user_list_userid_list_key);
                        Log::write('redis_batch_get_by_user_key:-----$userIdArr_tmp---' . json_encode($userIdArr_tmp, JSON_UNESCAPED_UNICODE));
                        !$userIdArr_tmp && $userIdArr_tmp = [];
                        Cache::set($this->redis_wxwork_company_worker_worker_id_key, json_encode($userIdArr_tmp, JSON_UNESCAPED_UNICODE), $expiration_time);
                    } else {
                        Cache::set($this->redis_wxwork_company_worker_worker_id_key, '', $expiration_time);
                    }
                } else {
                    $userIdArr_tmp = Cache::get($this->redis_wxwork_company_worker_worker_id_key, null);
                    $userIdArr_tmp && is_string($userIdArr_tmp) && $userIdArr_tmp = json_decode($userIdArr_tmp, true);
                }
                Log::write('redis_batch_get_by_user_key:-----userIdArr---' . json_encode($userIdArr_tmp, JSON_UNESCAPED_UNICODE));
                if($userIdArr_tmp) {
                    file_put_contents('./getBatchGetByUser.txt', json_encode($userIdArr_tmp) . PHP_EOL . PHP_EOL);
                    //最多只能是100个
                    $userIdArr = array_chunk($userIdArr_tmp, 100);
                    foreach($userIdArr as $index => $userId_item) {
                        Log::write('redis_batch_get_by_user_key:item:start:index:' . $index);
                        $result = $this->getBatchGetByUser($userId_item);
                        Log::write('redis_batch_get_by_user_key:item:end:index:' . $index);
                        Log::write('redis_batch_get_by_user_key:item:index:' . $index . ':result-result:' . json_encode($result, JSON_UNESCAPED_UNICODE));
                        if(isset($result) && $result) {
                            $_result = Cache::get($this->redis_batch_get_by_user_key, null);
                            !empty($_result) && is_string($_result) && $_result = json_decode($_result, true);
                            if(!empty($_result)) {
                                $result = array_merge($result, $_result);
                            }
                            Cache::set($this->redis_batch_get_by_user_key, json_encode($result, JSON_UNESCAPED_UNICODE), $expiration_time);
                        }
                    }
                }
            }
            Log::write('redis_batch_get_by_user_key:end');
        } catch(Exception $e) {
            Log::write('Exception:getMessage:' . $e->getMessage());
            throw new Exception($e->getMessage());
        }
        return true;
    }


    /**
     * @return true
     * @throws Exception
     */
    public function delRedis()
    {
        try {
            $result = Cache::get($this->redis_wxwork_depart_position_key, null);
            !empty($result) && is_string($result) && $result = json_decode($result, true);
            if(!empty($result)) {
                Cache::rm($this->redis_wxwork_depart_position_key);
            }
            $result = Cache::get($this->redis_wxwork_company_worker_key, null);
            !empty($result) && is_string($result) && $result = json_decode($result, true);
            if(!empty($result)) {
                Cache::rm($this->redis_wxwork_company_worker_key);
            }
            $result = Cache::get($this->redis_wxwork_company_customer_key, null);
            !empty($result) && is_string($result) && $result = json_decode($result, true);
            if(!empty($result)) {
                Cache::rm($this->redis_wxwork_company_customer_key);
            }
            $result = Cache::get($this->redis_wxwork_company_worker_key, null);
            !empty($result) && is_string($result) && $result = json_decode($result, true);
            if(!empty($result)) {
                Cache::rm($this->redis_wxwork_company_worker_key);
            }
            $result = Cache::get($this->redis_user_list_key, null);
            !empty($result) && is_string($result) && $result = json_decode($result, true);
            if(!empty($result)) {
                Cache::rm($this->redis_user_list_key);
            }
            $result = Cache::get($this->redis_batch_get_by_user_key, null);
            !empty($result) && is_string($result) && $result = json_decode($result, true);
            if(!empty($result)) {
                Cache::rm($this->redis_batch_get_by_user_key);
            }
        } catch(Exception $e) {
            throw new Exception($e->getMessage());
        }
        return true;
    }


    /**
     * @param $userIdArr
     * @param $cursor
     * @return array|mixed
     * @throws Exception
     */
    public function getBatchGetByUser($userIdArr, $cursor = '')
    {
        $result = QyApiWeixinServer::getExternalcontactBatchGetByUser($userIdArr, $this->access_token_txl, $cursor, 100);
        if(!empty($result['next_cursor'])) {
            $this->getBatchGetByUser($userIdArr, $result['next_cursor']);
        }
        return $result['external_contact_list'] ?? [];
    }

    /**
     * 拉取最新部门列表
     * @return true
     * @throws Exception
     */
    public function getCompanyDepart()
    {
        try {
            $time = get_now_time();
            $data = Cache::get($this->redis_department_list_key, null);
            !empty($data) && is_string($data) && $data = json_decode($data, true);
            if(!empty($data)) {
                foreach($data as &$item) {
                    $item['create_time'] = $time;
                }
                unset($item);
                Db::transaction(function() use ($data) {
                    Db::name('wxwork_depart')->delete(true);
                    Db::name('wxwork_depart')->insertAll($data);
                });
            }
            return true;
        } catch(Exception $e) {
            throw new Exception($e->getMessage());
        }
    }

    /**
     * 同步职位
     * @return true
     * @throws Exception
     * @throws InvalidArgumentException
     */
    public function getCompanyDepartPosition()
    {
        $new_data = Cache::get($this->redis_wxwork_company_worker_key, null);
        !empty($new_data) && is_string($new_data) && $new_data = json_decode($new_data, true);
        if(!empty($new_data)) {
            $_new_data = [];
            foreach($new_data as $item) {
                $_new_data[] = [
                    'depart_id' => $item['worker_main_department'],
                    'pos_name'  => $item['worker_position'],
                ];
            }
            $new_data = $_new_data;
        }
        $old_data = Cache::get($this->redis_wxwork_depart_position_key, null);
        !empty($old_data) && is_string($old_data) && $old_data = json_decode($old_data, true);
        $ins = [];
        if(!empty($old_data)) {
            if(!empty($new_data)) {
                $ins = get_diff_array_by_filter($new_data, $old_data);
            } else {
                $ins = $old_data;
            }
        } else {
            if(!empty($new_data)) {
                $ins = $new_data;
            }
        }
        if(!empty($ins)) {
            try {
                Db::transaction(function() use ($ins) {
                    Db::name('wxwork_depart_position')->insertAll($ins);
                });
            } catch(Exception $e) {
                throw new Exception($e->getMessage());
            }
        }


        return true;
    }

    /**
     * 获取企业成员保存到本地（第一步）
     * @return true
     * @throws Exception
     * @throws InvalidArgumentException
     */
    public function getCompanyWorker()
    {
        /*所有成员*/
        try {
            $result1 = QyApiWeixinServer::getUserList($this->access_token);
        } catch(Exception $e) {
            throw new Exception($e->getMessage());
        }
        /*所有成员，通过获取部门（顶级部门1来递归获取所有的）*/
        //本地成员
        $local_worker = Cache::get($this->redis_wxwork_company_worker_key, null);
        !empty($local_worker) && is_string($local_worker) && $local_worker = json_decode($local_worker, true);
        $local_worker_id_arr = [];
        if(!empty($local_worker)) {
            $local_worker_id_arr = array_column($local_worker, 'worker_id');
        }
        //成员数组
        $data1 = [];
        $data2 = [];
        if($result1) {
            //所有成员
            $arr2 = array_column($result1, 'userid');
            $data3 = array_diff($local_worker_id_arr, $arr2);
            foreach($result1 as $item) {
                if(!is_array($item)) {
                    $item = json_decode($item, true);
                }
                if($local_worker && isset($local_worker[$item['userid']])) {
                    $data1_tmp = [
                        'worker_id'              => $item['userid'],
                        'worker_name'            => $item['name'],
                        'worker_department'      => implode(',', $item['department']),
                        'worker_position'        => $item['position'],
                        'worker_mobile'          => $item['mobile'] ?? '',
                        'worker_status'          => $item['status'],
                        'worker_main_department' => $item['main_department']
                    ];
                    $found_tmp = [
                        'worker_id'              => $local_worker[$item['userid']]['worker_id'],
                        'worker_name'            => $local_worker[$item['userid']]['worker_name'],
                        'worker_department'      => $local_worker[$item['userid']]['worker_department'],
                        'worker_position'        => $local_worker[$item['userid']]['worker_position'],
                        'worker_mobile'          => $local_worker[$item['userid']]['worker_mobile'],
                        'worker_status'          => $local_worker[$item['userid']]['worker_status'],
                        'worker_main_department' => $local_worker[$item['userid']]['worker_main_department']
                    ];
                    $data1_tmp_md5 = md5(json_encode($data1_tmp, JSON_UNESCAPED_UNICODE));
                    $found_tmp_md5 = md5(json_encode($found_tmp, JSON_UNESCAPED_UNICODE));
                    if($data1_tmp_md5 != $found_tmp_md5) {
                        $data1_tmp['id'] = $local_worker[$item['userid']]['id'];
                        $data1_tmp['worker_cus'] = 1;
                        $data1[] = $data1_tmp;
                    }
                } else {
                    $data2_tmp = [
                        'worker_id'              => $item['userid'],
                        'worker_name'            => $item['name'],
                        'worker_department'      => $item['department'] ? implode(',', $item['department']) : '',
                        'worker_position'        => $item['position'],
                        'worker_mobile'          => $item['mobile'] ?? '',
                        'worker_status'          => $item['status'],
                        'worker_main_department' => $item['main_department'],
                        'worker_cus'             => 1
                    ];
                    $data2[] = $data2_tmp;
                }
            }
        } else {
            $data2 = $local_worker;
        }
        try {
            $data1 && BatchSqlServer::batchUpdate('la_wxwork_company_worker', $data1);

            $data2 && Db::name('wxwork_company_worker')->data($data2)->limit(5000)->insertAll($data2);

            $data3 && Db::name('wxwork_company_worker')
                ->where('worker_id', 'in', $data3)
                ->update([
                    'is_out'        => 2,
                    'worker_status' => 5
                ]);
        } catch(Exception $e) {
//            throw new Exception($e->getMessage());
            var_dump('getMessage====', $e->getMessage());
        }
        return true;
    }

    /**
     * 批量获取客户详情（第二步）
     * @param $only_me
     * @param $worker_id
     * @return true
     * @throws Exception
     * @throws InvalidArgumentException
     */
    public function getCompanyCustomerDetail($only_me = false, $worker_id = 0)
    {
        $userIdArr_tmp = Cache::get($this->redis_wxwork_company_worker_key, null);
        !empty($userIdArr_tmp) && is_string($userIdArr_tmp) && $userIdArr_tmp = json_decode($userIdArr_tmp, true);
        $userIdArr = [];
        if(!empty($userIdArr_tmp)) {
            //最多只能是100个
            $userIdArr = array_chunk($userIdArr_tmp, 100);
        }

        $local_customer_external_userid_arr = [];
        $local_customer = Cache::get($this->redis_wxwork_company_customer_key, null);
        !empty($local_customer) && is_string($local_customer) && $local_customer = json_decode($local_customer, true);
        if(!empty($local_customer)) {
            $_local_customer = [];
            if(!empty($local_customer)) {
                foreach($local_customer as $k => $v) {
                    $local_customer_external_userid_arr[] = $v['follow_userid'] . $v['external_userid'];
                    $_local_customer[md5($v['follow_userid'] . $v['external_userid'])] = $v;
                }
            }
            $local_customer = $_local_customer;
        }
        try {
            if($only_me === true) {
                $this->doGetCompanyCustomerDetail([$worker_id], $local_customer, $local_customer_external_userid_arr);
            } else {
                if($userIdArr) {
                    foreach($userIdArr as $item) {
                        $this->doGetCompanyCustomerDetail($item, $local_customer, $local_customer_external_userid_arr);
                    }
                }
            }
//            }
        } catch(Exception $e) {
            throw new Exception($e->getMessage());
        }
        return true;
    }

    /**
     * 批量获取客户详情（第二步）
     * @param $userIdArr
     * @param $local_customer
     * @param $local_customer_external_userid_arr
     * @param $cursor
     * @return true
     * @throws Exception
     */
    public function doGetCompanyCustomerDetail($userIdArr, $local_customer, $local_customer_external_userid_arr, $cursor = '')
    {
        $data1 = [];
        $data2 = [];
        try {
            $result = Cache::get($this->redis_batch_get_by_user_key, null);
            !empty($result) && is_string($result) && $result = json_decode($result, true);
            if(!$result) {
                throw new Exception('获取失败：get:redis_batch_get_by_user_key');
            }

        } catch(Exception $e) {
            throw new Exception($e->getMessage());
        }
        $up_people = '批量';
        foreach($result as $item) {
            if(!is_array($item)) {
                $item = json_decode($item, true);
            }
            if($item) {
                $tmp = [
                    'external_name'           => $item['external_contact']['name'],
                    'external_type'           => $item['external_contact']['type'],
                    'external_corp_name'      => '',
                    'external_corp_full_name' => '',
                    'follow_state'            => $item['follow_info']['state'] ?? '',
                    'follow_userid'           => $item['follow_info']['userid'],
                    'follow_remark'           => $item['follow_info']['remark'],
                    'follow_description'      => $item['follow_info']['description'],
                    'follow_createtime'       => $item['follow_info']['createtime'],
                    'follow_tag_id'           => $item['follow_info']['tag_id'] ? implode(',', $item['follow_info']['tag_id']) : '',
                    'follow_remark_mobiles'   => $item['follow_info']['remark_mobiles'] ? implode(',', $item['follow_info']['remark_mobiles']) : '',
                    'follow_add_way'          => $item['follow_info']['add_way'],
                    'external_userid'         => $item['external_contact']['external_userid'] ?? '',
                    'external_avatar'         => $item['external_contact']['avatar'],
                    'external_gender'         => $item['external_contact']['gender'],
                ];
                if($tmp['external_type'] == 2) {
                    $tmp['external_corp_name'] = $item['external_contact']['corp_name'] ?? '';
                    $tmp['external_corp_full_name'] = $item['external_contact']['corp_full_name'] ?? '';
                } else {
                    $tmp['external_corp_name'] = $item['follow_info']['remark_corp_name'] ?? '';
                }
                $follow_userid_external_userid_md5 = md5($tmp['follow_userid'] . $tmp['external_userid']);
                if(isset($local_customer[$follow_userid_external_userid_md5])) {
                    $found_tmp = [
                        'follow_userid'           => $local_customer[$follow_userid_external_userid_md5]['follow_userid'],
                        'follow_remark'           => $local_customer[$follow_userid_external_userid_md5]['follow_remark'],
                        'follow_description'      => $local_customer[$follow_userid_external_userid_md5]['follow_description'],
                        'follow_createtime'       => $local_customer[$follow_userid_external_userid_md5]['follow_createtime'],
                        'follow_tag_id'           => $local_customer[$follow_userid_external_userid_md5]['follow_tag_id'],
                        'follow_remark_mobiles'   => $local_customer[$follow_userid_external_userid_md5]['follow_remark_mobiles'],
                        'follow_add_way'          => $local_customer[$follow_userid_external_userid_md5]['follow_add_way'],
                        'external_userid'         => $local_customer[$follow_userid_external_userid_md5]['external_userid'],
                        'external_name'           => $local_customer[$follow_userid_external_userid_md5]['external_name'],
                        'external_type'           => $local_customer[$follow_userid_external_userid_md5]['external_type'],
                        'external_corp_name'      => $local_customer[$follow_userid_external_userid_md5]['external_corp_name'],
                        'external_corp_full_name' => $local_customer[$follow_userid_external_userid_md5]['external_corp_full_name'],
                        'follow_state'            => $local_customer[$follow_userid_external_userid_md5]['follow_state'],
                        'external_avatar'         => $local_customer[$follow_userid_external_userid_md5]['external_avatar'],
                        'external_gender'         => $local_customer[$follow_userid_external_userid_md5]['external_gender']
                    ];
                    if($tmp != $found_tmp) {
                        if(isset($item['external_contact']['unionid'])) {
                            $tmp['external_unionid'] = $item['external_contact']['unionid'];
                        }
                        $tmp['is_out'] = 1;
                        $tmp['update_time'] = get_now_date();
                        $tmp['update_people'] = $up_people;
                        $tmp['id'] = $local_customer[$follow_userid_external_userid_md5]['id'];
                        if($tmp['remark_mobiles']) {
                            $remark_mobiles = explode(',', $tmp['follow_remark_mobiles']);
                            if($remark_mobiles) {
                                $_remark_mobiles = '';
                                foreach($remark_mobiles as $mobile) {
                                    if(is_phone($mobile)) {
                                        $_remark_mobiles = $mobile;
                                        break;
                                    }
                                }
                                $tmp['follow_remark_mobiles_hash'] = $_remark_mobiles;
                            }
                        }
                        $data1[] = $tmp;
                    }
                } else {
                    if(isset($item['external_contact']['unionid'])) {
                        $tmp['external_unionid'] = $item['external_contact']['unionid'];
                    }
                    $tmp['is_out'] = 1;
                    if($tmp['remark_mobiles']) {
                        $remark_mobiles = explode(',', $tmp['follow_remark_mobiles']);
                        if($remark_mobiles) {
                            $_remark_mobiles = '';
                            foreach($remark_mobiles as $mobile) {
                                if(is_phone($mobile)) {
                                    $_remark_mobiles = $mobile;
                                    break;
                                }
                            }
                            $tmp['follow_remark_mobiles_hash'] = $_remark_mobiles;
                        }
                    }
                    $data2[] = $tmp;
                }
            }
        }
        try {
            if(!empty($data1)) {
                BatchSqlServer::batchUpdate('la_wxwork_company_customer', $data1);
            }
            if(!empty($data2)) {
                Db::name('wxwork_company_customer')->data($data2)->limit(5000)->insertAll($data2);
            }
        } catch(Exception $e) {
            throw new Exception($e->getMessage());
        }
        return true;
    }


}
